package com.ruoyi.web.controller.system;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.ruoyi.com.domain.ComUserDept;
import cn.hutool.core.date.DateUtil;
import com.ruoyi.com.domain.vo.ChangeSmallVo;
import com.ruoyi.com.mapper.ComUserDeptMapper;
import com.ruoyi.com.service.IComMenuService;
import com.ruoyi.com.service.IComUserService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.core.domain.model.LoginTokenBody;
import com.ruoyi.common.core.domain.model.LoginUnitfUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.framework.web.service.TokenUnitfService;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMenuService;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController extends BaseController
{
//
//    @Value("${system.parentMenuId}")
//    private String parentMenuId;

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private IComMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private IComUserService userService;

    @Autowired
    private ComUserDeptMapper comUserDeptMapper;

    @Autowired
    private TokenUnitfService tokenUnitfService;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private ISysDictDataService dictDataService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    @ApiOperation(value = "登录接口")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        String username = loginBody.getUsername();
        String password = loginBody.getPassword();
        String code = loginBody.getCode();
        String uuid = loginBody.getUuid();
        // 验证码校验
        loginService.validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginService.loginPreCheck(username, password);
        ComUser comUser = userService.selectUserByUsername(username);
        if (StringUtils.isNull(comUser))
        {
            throw new ServiceException("当前用户不存在，请联系管理员！");
        }
        else if (UserStatus.DELETED.getCode().equals(comUser.getDelFlag()))
        {
            throw new ServiceException("当前用户不存在，请联系管理员！");
        }
        if (!loginService.matches(comUser,password)) {
            throw new ServiceException("密码不正确");
        }
        // 查询机构
        List<SysDept> deptList = comUserDeptMapper.selectComUserDeptByUserId(comUser.getUserId());
        if(deptList ==null || deptList.size()==0){
            throw new ServiceException("该用户暂无机构");
        }
        if(deptList !=null && deptList.size() ==1){
            SysDept sysDept = deptList.get(0);
            //查看该机构下用户和是否为管理员
            ComUserDept comUserDept = comUserDeptMapper.selectUserStatusByUserIdAndDeptId(comUser.getUserId(),sysDept.getDeptId());
            if(comUserDept==null || comUserDept.getStatus().intValue()==1){
                throw new ServiceException("该用户被禁用");
            }
            Long isAdmin = comUserDept.getIsAdmin();
            comUser.setIsAdmin(isAdmin);
            comUser.setIsMultipleDept(false);
            LoginUnitfUser loginAppUser = new LoginUnitfUser(comUser.getUserId(),sysDept.getDeptId(),sysDept.getDeptName(),comUser);
            loginService.recordLoginInfo(loginAppUser.getUserId());
            // 生成token
            String token = tokenUnitfService.createToken(loginAppUser);
            AjaxResult ajax = success();
            ajax.put(Constants.TOKEN, token);
            return ajax;
        }else{
            AjaxResult ajax = success();
            LoginUnitfUser loginAppUser = new LoginUnitfUser(comUser.getUserId(),null,null,comUser);
            //生成临时toke
            String tempToken = tokenUnitfService.createTempToken(loginAppUser);
            ajax.put("tempToken", tempToken);
            return ajax;
        }
    }


    /**
     * 根据临时token获取登录token
     *
     * @return 结果
     */
    @PostMapping("/tempTokenGetToken")
    @ApiOperation(value = "根据临时token获取登录token")
    public AjaxResult tempTokenGetToken(@RequestBody LoginTokenBody loginBody)
    {
        if(loginBody.getDeptId()==null){
            throw new ServiceException("请选择机构");
        }
        SysDept sysDept = sysDeptMapper.selectDeptById(loginBody.getDeptId());
        if(sysDept==null){
            throw new ServiceException("请选择机构");
        }
        LoginUnitfUser loginUntifyUser = SecurityUtils.getLoginTempUser(loginBody.getTempToken());
        ComUser comUser = loginUntifyUser.getUser();
        //查看该机构下用户和是否为管理员
        ComUserDept comUserDept = comUserDeptMapper.selectUserStatusByUserIdAndDeptId(comUser.getUserId(),sysDept.getDeptId());
        if(comUserDept==null || comUserDept.getStatus().intValue()==1){
            throw new ServiceException("该用户被禁用");
        }
        Long isAdmin = comUserDept.getIsAdmin();
        comUser.setIsAdmin(isAdmin);
        comUser.setIsMultipleDept(true);
        LoginUnitfUser loginAppUser = new LoginUnitfUser(loginUntifyUser.getUserId(),loginBody.getDeptId(),sysDept.getDeptName(),loginUntifyUser.getUser());
        loginService.recordLoginInfo(loginAppUser.getUserId());
        // 生成token
        String token = tokenUnitfService.createToken(loginAppUser);
        AjaxResult ajax = success();
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }


    /**
     * 临时token查询机构列表分页
     *
     * @return 结果
     */
    @PostMapping("/tempTokenGetDeptList")
    @ApiOperation(value = "临时token查询机构列表分页")
    public AjaxResult deptLoginGetToken(@RequestBody LoginTokenBody loginBody)
    {
        startPage();
        LoginUnitfUser loginUntifyUser = SecurityUtils.getLoginTempUser(loginBody.getTempToken());
        List<SysDept> deptList = comUserDeptMapper.selectComUserDeptByUserId(loginUntifyUser.getUserId());
        return success(getDataTable(deptList));
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        ComUser user = SecurityUtils.getLoginUser().getUser();
        String deptName = SecurityUtils.getLoginUser().getDeptName();
        user.setDeptName(deptName);//机构名称
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions",permissions);
       return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        LoginUnitfUser loginUser = SecurityUtils.getLoginUser();
        List<ComMenu> menus = menuService.selectMenuTreeByUserId(loginUser);
        return AjaxResult.success(menuService.buildMenus(menus));
    }



    /**
     * 获取统一平台跳转路径
     *
     */
    @GetMapping("getTongYiSystemUrl")
    @ApiOperation(value = "获取统一平台跳转路径")
    public AjaxResult getTongYiSystemUrl()
    {
        String url = dictDataService.getTongYiSystemUrl();
        return AjaxResult.success(url);
    }


    /**
     * 查询用户拥有的小程序
     *
     * @return 结果
     */
    @PostMapping("/selectUserHaveSmall")
    @ApiOperation(value = "查询用户拥有的小程序")
    public AjaxResult selectUserHaveSmall()
    {
        LoginUnitfUser loginUntifyUser = SecurityUtils.getLoginUser();
        ComUser user = loginUntifyUser.getUser();
        Long deptId = loginUntifyUser.getDeptId();
        List<ComMenu> list = menuService.selectUserHaveSmall(user,deptId);
        return success(list);
    }


    /**1
     * 切换小程序
     */
    @PostMapping("/changeSmall")
    @ApiOperation(value = "切换小程序")
    public AjaxResult changeSmall(@RequestBody ChangeSmallVo changeSmallVo)
    {
        LoginUnitfUser loginUntifyUser = SecurityUtils.getLoginUser();
        Long deptId = loginUntifyUser.getDeptId();
        ComUser comUser = loginUntifyUser.getUser();
        comUser.setSmallId(changeSmallVo.getSmallId());
        comUser.setIsMultipleSmall(changeSmallVo.getIsMultipleSmall());
        comUser.setType(changeSmallVo.getType());
        comUser.setSmallName(changeSmallVo.getSmallName());
        LoginUnitfUser loginAppUser = new LoginUnitfUser(loginUntifyUser.getUserId(),deptId,loginUntifyUser.getDeptName(),comUser);
        // 刷新token
        loginAppUser.setToken(loginUntifyUser.getToken());
        tokenUnitfService.refreshToken(loginAppUser);
        return success();
    }



    /**
     * 服务器时间
     */
    @RequestMapping("/sysTime")
    @ApiOperation(value = "获取服务器时间")
    public AjaxResult sysTime() {
        return AjaxResult.success(DateUtil.formatDateTime(new Date()));
    }
}
